<?php

/**
 * This file contains a logging mechanism
 *
 * @author Sven Ruttloff, www.sruttloff.de <service@sruttloff.de>
 * @copyright S.Ruttloff, Computer Hard- & Software
 * @package core
 * @license http://www.sruttloff.de/cms/files/licence_en_lgpl.txt LGPL
 */

/**
 * logging
 *
 * @package core
 * @version 1
 */

class logging
{
    /**
     * @var object instance
     */
    private static $INSTANCE;

    /**
    * @var string   logging type
    */
    private $LTYPE = null;
    /**
    * @var string   name of log. destination
    */
    private $LDESTINATION = null;
    /**
    * @var array event store
    */
    private $LEVENT = array();
    /**
     * instantiate essential objects and make them avail. as subobjects
     * @param string session name (optional)
     * @return  void
     */
    private function __construct() {

    }
    /**
     * return a instance of object
     *
     * @param string logging type, default file
     * @param string where to store logging datas
     * @return object instance
     */
    public static function getInstance($type = 'file', $filename = './logging.log') {
        if (!isset(self::$INSTANCE))
        {
            $c = __CLASS__;
            self::$INSTANCE = new $c ($sessionname);
            self::$INSTANCE->LTYPE = strtolower($type);
            self::$INSTANCE->LDESTINATION = $filename;
        }
        return self::$INSTANCE;
    }
    /**
     * add line to log
     *
     * @param string event name of log. entry
     * @param string some conent more (! only one line please)
     * @return bool
     */
    public function addEvent ($eventname = null, $text)
    {
        $array['DateTime'] = date ('Y-m-d H:i:s');
        $array['EVENT'] = $eventname . ' :: ' . $text;
        $this->LEVENT[] = implode(' > ', $array);
        return true;
    }
    public function __destruct()
    {
        try
        {
            if ($this->LTYPE == 'file')
            {
                $frontend = frontend::getInstance();;
                if ($frontend->getConfig()->Get('chmod_file'))
                    $res = create_file($this->LDESTINATION, implode ("\r\n", $this->LEVENT, $frontend->getConfig()->Get('chmod_file')));
                else
                    $res = create_file($this->LDESTINATION, implode ("\r\n", $this->LEVENT));
            }
            else
            {
                /**
                 * may DB type?
                 * ToDo:
                 *
                 */

            }
            if (!$res)
                throw new Exception('write fail #' . __LINE__);
        }
        catch (Exception $e )
        {
            trigger_error($e->getMessage(), E_USER_ERROR);
        }

    }
    public function store ()
    {
        $this->__destruct();
        return true;
    }
}
